﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Xml;
using System.Text;
using System.Collections.Generic;
using EFFC.Net.Parameters;
using EFFC.Net.Returns;
using EFFC.Net.Resource;
using EFFC.Net.Data.DBData;
using EFFC.Net.WebBuilder.WebPage;
using EFFC.Net.WebBuilder.Public;
using System.Reflection;
using System.ComponentModel;
using EFFC.Net.Interface;
using EFFC.Net.WebBuilder.Parameters;

namespace EFFC.Net.WebBuilder.WebPage
{
    public abstract class AuthorizedPageBase : WebPageBase
    {
        protected abstract void Page_OnLoad();
        private string _functionid = "";
        private string _actionid = "";
        private string _operatorItem = "";
      
        /// <summary>
        /// 本页面被授权的FunctionID
        /// </summary>
        public string FunctionID
        {
            get
            {
                return _functionid;
            }
        }
        /// <summary>
        /// 当前触发事件的ActionID，当PageAction.config设定的button对应的Action较多时则默认为第一个
        /// </summary>
        public string ActionID
        {
            get
            {
                return _actionid;
            }
        }

        #region 登入者資訊相關的Session
        /// <summary>
        /// 當前用戶信息
        /// </summary>
        public string UserID
        {
            get { return Session[SessionAndCookieKeys.LoginUserModule] == null ? "" : ((LoginUserModule)Session[SessionAndCookieKeys.LoginUserModule]).UserID; }
        }
        /// <summary>
        /// 當前用戶信息
        /// </summary>
        public string UserName
        {
            get { return Session[SessionAndCookieKeys.LoginUserModule] == null ? "" : ((LoginUserModule)Session[SessionAndCookieKeys.LoginUserModule]).UserName; }
        }
        /// <summary>
        /// 當前用戶所屬角色
        /// </summary>
        public string RoleID
        {
            get { return Session[SessionAndCookieKeys.LoginUserModule] == null ? "" : ((LoginUserModule)Session[SessionAndCookieKeys.LoginUserModule]).RoleID; }
        }

        /// <summary>
        /// 當前用戶的權限列表
        /// </summary>
        protected string UserActions
        {
            get { return Session[SessionAndCookieKeys.LoginUserModule] == null ? null : ((LoginUserModule)Session[SessionAndCookieKeys.LoginUserModule]).Actions.GetActionIDsByFunctionID(FunctionID); }
        }
        #endregion

        public override void OnPageLoad()
        {
            //判斷Session是否超時
            if (Session == null || HttpContext.Current.Session == null || Session[SessionAndCookieKeys.LoginUserModule] == null)
            {
                Redirect("~/Login.aspx");
                return;
            }

            string steErr = "";
            string strPath = this.BaseRequest.Url.LocalPath;
            

            LoginUserModule lum = (LoginUserModule)Session[SessionAndCookieKeys.LoginUserModule];
            //基本權限判斷-------------------------------------------------------------------------------
            if (lum != null)//有用戶信息
            {
                //當前登錄ID
                string currentUserid = lum.UserID;
                //被代理人ID
                string agentUserID = "";
                if (!string.IsNullOrEmpty(lum.AgentID))
                {
                    agentUserID = lum.AgentID;
                }

                if (lum.Actions.HasActions)//有權限信息
                {
                        if (lum.Actions.GetActionIDsByPageUrl(strPath) == "")//沒有訪問本頁的權限
                        {
                            steErr = "沒有訪問本頁權限";
                            RegisterScriptAndGoTo("alert('" + steErr + "');", "~/Default.aspx");

                            return;
                        }
                    
                }
                else
                {
                    steErr = "沒有角色權限";
                    RegisterScriptAndGoTo("alert('" + steErr + "');", "~/Login.aspx");
                }
            }

            if (steErr == "")
            {
                _functionid = lum.Actions.GetFunctionIDByPageUrl(strPath);
                if (this.Master != null)
                {
                    HiddenField hid_FunctionId = this.Master.FindControl("hid_ParentFunctionID") as HiddenField;
                    hid_FunctionId.Value = lum.Actions.GetParentFunctionIDByPageUrl(strPath);
                }
                Page_OnLoad();
            }

            
        }

        protected override void OnLoadComplete(EventArgs e)
        {
            if (Session == null || HttpContext.Current.Session == null || Session[SessionAndCookieKeys.LoginUserModule] == null)
            {
                return;
            }



            base.OnLoadComplete(e);
            //进行button的权限设定
            foreach (Control iap in _controls_Permission.Values)
            {
                ((IActionPermission)iap).ControlByPermission(UserActions);
            }

        }

        protected override void BeforeEventRaise(IPostBackEventHandler sourceControl, string eventArgument)
        {
            base.BeforeEventRaise(sourceControl, eventArgument);
            if (sourceControl is IActionPermission)
            {
                if (sourceControl is Button)
                {
                    _operatorItem = ((Button)sourceControl).Text;
                    _actionid = ((IActionPermission)sourceControl).ActionID;
                }
                else if (sourceControl is LinkButton)
                {
                    _operatorItem = ((LinkButton)sourceControl).Text;
                    _actionid = ((IActionPermission)sourceControl).ActionID;
                }
            }
        }

        /// <summary>
        /// 跳到指定頁面
        /// </summary>
        /// <param name="url"></param>
        public void MainFreamGoPage(string url)
        {
            StringBuilder script = new StringBuilder();
            script.Append("if(opener != null){");
            script.Append("opener.window.parent.location='" + url + "';window.close();");
            script.Append("}else{");
            script.Append("window.parent.location='" + url + "';}");

            //ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), string.Concat("window.parent.location='", url, "';"), true);
            ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), script.ToString(), true);
        }

        /// <summary>
        /// 获取页面参数
        /// </summary>
        /// <param name="map"></param>
        /// <returns></returns>
        public WebManageParameter GetPageParameters(APageMapping map)
        {
            WebManageParameter rtn = new WebManageParameter();
            rtn.LoginUserID = UserID;
            rtn.LoginUser = UserName;
            rtn.AgentUserID = "";
            rtn.FunctionID = _functionid;
            rtn.ActionID = _actionid;
            rtn.SetValue("UserItem", _operatorItem);
            rtn.Module = GetModule(map);
            return rtn;
        }
        /// <summary>
        /// 獲取頁面參數
        /// </summary>
        /// <returns></returns>
        public WebManageParameter GetPageParameters()
        {
            WebManageParameter rtn = new WebManageParameter();
            rtn.LoginUserID = UserID;
            rtn.LoginUser = UserName;
            rtn.AgentUserID = "";
            rtn.FunctionID = _functionid;
            rtn.ActionID = _actionid;
            rtn.SetValue("UserItem", _operatorItem);
            rtn.Module = GetModule();
            return rtn;
        }
        /// <summary>
        /// 根据Mapping和module设置页面的数据值
        /// </summary>
        /// <param name="map"></param>
        /// <param name="pm"></param>
        public void SetPageValues(APageMapping map, PageModule pm)
        {
            base.SetModuleValue(map, pm);
        }

       
        /// <summary>
        /// 判斷用戶是否有某個權限
        /// </summary>
        /// <param name="functionid">某功能編碼</param>
        /// <param name="userFunctions">用戶權限功能編碼集</param>
        /// <param name="actionid">權限編碼</param>
        /// <returns>true：有,false：沒有</returns>
        protected bool CanUseAction(string actionid)
        {
            if (actionid == null || actionid == "")
            {
                return false;
            }
            if (actionid.Contains(","))
            {
                return CanUseAction(actionid.Split(",".ToCharArray()));
            }
            else
            {
                if (this.UserActions != null)
                    return this.UserActions.Contains(actionid);
                else
                    return false;
            }
        }

        /// <summary>
        /// 判斷用戶是否有某個權限
        /// </summary>
        /// <param name="actionid">某功能可用編碼</param>
        /// <returns>true：有,false：沒有</returns>
        protected bool CanUseAction(params string[] actionid)
        {

            for (int index = 0; index < actionid.Length; index++)
            {
                if (this.UserActions.Contains(actionid[index].Trim()))
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 獲取頁面所有功能權限
        /// </summary>
        /// <param name="strPath"></param>
        /// <returns></returns>
        public string GetPageActionsID()
        {

            XmlElement Page = null, Pages = null, root = null;
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(Server.MapPath("/PageAction.config"));
            root = xmldoc.DocumentElement;

            Pages = (XmlElement)root.SelectSingleNode("Pages");
            Page = (XmlElement)Pages.SelectSingleNode("Page");

            //SQLServerAccess dba = new SQLServerAccess();
            //dba.Open(MyConfig.GetConnections("dbConn"));
            //DBAP p = new DBAP();
            //p.SQL = "select *  FROM vwFuncsActions WHERE FunctionUrl = '" + strPath + "'";
            //DataSetStd dts = dba.Query(p);
            //dba.Close();

            //string ActionsID = "";
            //if (dts != null && dts[0].RowLength > 0)
            //{
            //    foreach (DataRow dr in dts.Tables[0].Rows)
            //    {
            //        ActionsID += dr["ActionID"].ToString() + ',';
            //    }
            //}
            //return ActionsID;
            return "";
        }

        /// <summary>
        /// 查找控制項
        /// </summary>
        /// <param name="name">控制項名稱</param>
        /// <returns>控制項</returns>
        protected object FindCtrl(string name)
        {
            if (this.Master == null)//如果是有主版
            {
                return this.FindControl(name);
            }
            else
            {
                return ((MasterBase)this.Master).GetContral(name);
            }
        }


        /// <summary>
        /// 为了Excel导出需要重载该方法
        /// </summary>
        /// <param name="control"></param>
        public override void VerifyRenderingInServerForm(Control control)
        {
            //注释掉下面的代码，否则在asp.net2.0下会报错
            // base.VerifyRenderingInServerForm(control);
        }


    }
}
